package com.clx.service.impl;

import com.clx.constants.SystemConstants;
import com.clx.domain.ResponseResult;
import com.clx.domain.entity.LoginUser;
import com.clx.domain.entity.User;
import com.clx.domain.vo.LoginVo;
import com.clx.domain.vo.UserInfoVo;
import com.clx.service.BlogLoginService;
import com.clx.utils.BeanCopyUtils;
import com.clx.utils.JwtUtil;
import com.clx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(token);
        // 判断是否认证通过
        if (Objects.isNull(authentication)) {
            throw new RuntimeException("用户名密码错误");
        }
        // 获取userId 生成 token
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String Jwt = JwtUtil.createJWT(userId.toString());
        // 将用户信息存入redis
        redisCache.setCacheObject(SystemConstants.LOGIN_KEY_PREV + userId.toString(), loginUser);
        // 将token和userinfo进行封装
        LoginVo loginVo = new LoginVo(Jwt, BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class));
        return ResponseResult.okResult(loginVo);
    }

    @Override
    public ResponseResult logout() {
        // 获取token
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 解析获取userId
        Long userId = loginUser.getUser().getId();
        // 删除redis中的用户信息
        redisCache.deleteObject(SystemConstants.LOGIN_KEY_PREV + userId);
        return ResponseResult.okResult();
    }


}
